// pages/indexDetail/indexDetail.js
const Page = require('../../utils/ald-stat.js').Page;
import * as echarts from '../../ec-canvas/echarts';
const http = require('../../api/http.js');
var app = getApp();
var areaChart = null;
var columnChart = null;
var columnYearChart = null;
let chart = null;
Page({
  data: {
    isShow: false, //弹窗显示
    id: '', //接收首页传过来的id
    brandDetail: {}, //品牌详情
    thumbsList: [], //点赞列表
    showPopup: false, //是否出现弹窗
    indexNumValue: [], //指数波动表值
    indexNumMonth: [], //指数波动表月份
    monthNumValue: [], //月份对应的值
    paperNumMonth: [], //月份
    yearNumValue: [], //年份对应的值
    paperNumYear: [], //年份
    access_token: '', //请求官方接口生成的token
    codeUrl: '', //生成的二维码路径
    brandName: '', //品牌名字
    indexScore: '', //指数值
    brandBrief: '', //品牌简介
    provider: '', //生产商
    address: '', //经营地址
    showPhoto: false, //生成图片的弹窗，
    no_is: 0, //
    next: '', //后台字段返回的next值
    page: 1, //默认页数
    showMore: false, //是否还有更多
    flag: 0,
    isHand: false, //是否点赞
    imgUrl: '',    //后台返回的二维码图片路径
    count: '', //点赞人数
    showTips: false, //sci论文提示弹窗
    showIndexTips: false, //知了指数波动表提示弹窗
    saveTips: false, //图片保存成弹窗
    home:true,         //是否从首页到这个页面
    data: '',
    monthBar: {
      lazyLoad: true // 延迟加载
    },
    indexLine: {
      lazyLoad: true // 延迟加载
    },
    yearBar: {
      lazyLoad: true // 延迟加载
    },
    width: 0,
    height: 0,
  },
  onLoad: function(options) {
    let _this = this;
    //获取首页传递过来的品牌id
    if(options.home){
      _this.setData({
      home:false
      })
    }
    if (options.scene){
      const scene = decodeURIComponent(options.scene);
      let id= scene.split('=')[1];
      _this.setData({
        id: id
      })
    }else{
      _this.setData({
        id: options.id,
      })
    }
    //请求是否点赞接口
    this.isThumbs();
    //调用年度和月度，知了指数波动表接口请求数据
    this.http_getmonthPaper();
    this.http_getyearPaper();
    this.http_getIndex();
    //调用品牌详情和点赞列表
    this.http_brandDetail();
    this.http_getThumbs();
    //点击右上角三个点可以分享
    wx.showShareMenu({
      withShareTicket: true
    })
   
  },
  onReady() {
    let _this = this;
    //调用初始化图表的接口
    setTimeout(function () {
      _this.init_indexLine();
      _this.init_monthBar();
      _this.init_yearBar();
    }, 500)
  },
  onShow: function() {


  },
  //请求品牌详情接口
  http_brandDetail() {
    let id = this.data.id;
    http.getBrandDetail(id, res => {
      this.setData({
        brandDetail: res.result
      })
      this.setData({
        brandName: res.result.name,
        indexScore: res.result.cicada_index.toFixed(1),
        brandBrief: res.result.intro,
        provider: res.result.manufacturer,
        address: res.result.manu_address,
      })
    }, err => {});
  },
  //SCI论文引用的提示弹窗
  tipsEvent() {
    this.setData({
      showTips: true
    })
  },
  //关闭SCI论文提示弹窗
  closeEvent() {
    this.setData({
      showTips: false
    })
  },
  //知了指数波动表提示弹窗
  tipsIndexEvent() {
    this.setData({
      showIndexTips: true
    })
  },
  //关闭指数波动表提示弹窗
  closeIndexEvent() {
    this.setData({
      showIndexTips: false
    })
  },
  //图片保存成功提示弹窗
  knowSave() {
    this.setData({
      saveTips: false
    })
  },
  //点击查看详情，跳转至论文详情页面
  topaperDetail() {
    wx.navigateTo({ //保留当前页面，跳转到应用内的某个页面（最多打开5个页面，之后按钮就没有响应的）
      url: "/pages/paperDetail/paperDetail?id=" + this.data.id,
      success: function() {},
      fail: function() {
      }
    })
  },
  //请求点赞列表
  http_getThumbs() {
    let id = this.data.id;
    http.getThumbs(id, this.data.page, res => {
      this.setData({
        thumbsList: res.result,
        count: res.count,
        next: res.next
      })
      if (res.result.length < res.count) {
        this.setData({
          showMore: true,
        })
      }
    }, err => {});
  },
  //点赞区域上拉加载更多
  lower(){
   let _this=this;
   let id = this.data.id;
   if(_this.data.next!=null){
     _this.setData({
       page: _this.data.page + 1
     })
     http.getThumbs(id, _this.data.page,res=>{
       _this.setData({
         thumbsList: _this.data.thumbsList.concat(res.result),
         next: res.next
       })
       if (_this.data.thumbsList.length>=res.count){
         _this.setData({
           showMore: false,
         })
       }
     },err=>{

     })
   }
  },
  //请求知了指数波动表
  http_getIndex() {
    let id = this.data.id;
    http.getIndex(id, res => {
      for (let item of res.result) {
        this.data.indexNumValue.unshift(item.value.toFixed(2));
        let arr = item.ym_time.split('-')[1] + '月';
        this.data.indexNumMonth.unshift(arr);
      }
    }, err => {});
  },
  //请求月度论文引用数量接口
  http_getmonthPaper() {
    let _this=this;
    let id = this.data.id;
    let groupby = 'month'
    http.getPaperNum(id, groupby, res => {
      for (let item of res.result) {
        this.data.monthNumValue.unshift(item.amount);
        let arr = item.month.split('-')[1] + '月';
        this.data.paperNumMonth.unshift(arr);
      }
    }, err => {});
  },
  //请求年度论文引用数量接口
  http_getyearPaper() {
    let id = this.data.id;
    let groupby = 'year'
    http.getPaperNum(id, groupby, res => {
      for (let item of res.result) {
        this.data.yearNumValue.unshift(item.amount);
        let arr = item.year;
        this.data.paperNumYear.unshift(arr);
      }
    }, err => {});
  },
  //初始化图表
  init_indexLine() {
    this.selectComponent('#mychart-dom-index-bar').init((canvas, width, height) => {
      // 初始化图表
      const barChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      barChart.setOption(this.getindexLineOption());
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return barChart;
    });
  },
  init_monthBar() {
    this.selectComponent('#mychart-dom-month-bar').init((canvas, width, height) => {
      this.setData({
        width: width,
        height: height,
      })
      // 初始化图表
      const barChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      barChart.setOption(this.getMonthBarOption());
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return barChart;
    });
  },
  init_yearBar() {
    this.selectComponent('#mychart-dom-year-bar').init((canvas, width, height) => {
      // 初始化图表
      const barChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      barChart.setOption(this.getYearBarOption());
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return barChart;
    });
  },
  //指数波动表配置
  getindexLineOption() {
    let _this = this;
    let option = {
      title: {
        left: 'center',
        bottom: 10,
        text: '知了指数波动表',
        textStyle: {
          color: '#333333',
          fontSize: 13
        },
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          interval: 1
        },
        data: _this.data.indexNumMonth,
        // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      yAxis: {
        type: 'value',
        name: '知了指数值',
        nameLocation: 'center',
        nameGap:35,
        nameTextStyle: {
          color: '#333',
          fontSize: 10,
        },

      },
      series: [{
        smooth: true, //把线变为曲线
        data: this.data.indexNumValue,
        // data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line',
        itemStyle: {
          normal: {
            type: 'linear',
            label: {
              show: false
            },
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [{
                  offset: 0,
                  color: '#0098FF'
                },
                {
                  offset: 1,
                  color: '#fff'
                }
              ]
            ),
            //柱形图圆角，初始化效果
            barBorderRadius: [10, 10, 0, 0],
          }
        },
        areaStyle: {}
      }],
      grid: {
        left: '50',
        right: '4%',
        top: 10,
      },
    }
    return option;
  },
  //月度表的配置
  getMonthBarOption() {
    let _this = this;
    // console.log(_this.data, '222')
    var option = {
      color: ['#3398DB'],
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        },
        triggerOn:'click',
        // alwaysShowContent:false,
        confine:true,    //是否将提示框限制在图表内
        formatter(params, ticket, callback) {
          var resTips=params[0].name+'\n'+'论文引用数量：'+params[0].value
          return resTips;
        }
        // position: function(pos, params, dom, rect, size) {
        //   // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
        //   var obj = {
        //     top: 60
        //   };
        //   obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
        //   return obj;
        // },

      },
      grid: {
        left: 30,
        right: '4%',
        // bottom: '3%',
        top: 10
      },
      xAxis: [{
        type: 'category',
        data: _this.data.paperNumMonth,
        // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        axisTick: {
          alignWithLabel: true
        }
      }],
      yAxis: [{
        type: 'value',
        max: function(value) {
          return value.max +value.max*0.2;
        }
      }],
      series: [{
        name: '',
        type: 'bar',
        barWidth: '40%',
        data: _this.data.monthNumValue,
        //  data: [10, 52, 200, 334, 390, 330, 220],
        itemStyle: {
          normal: {
            type: 'linear',
            label: {
              show: false
            },
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [{
                  offset: 0,
                  color: '#6DE9F0'
                },
                {
                  offset: 1,
                  color: '#3F8CE5'
                }
              ]
            ),
            //柱形图圆角，初始化效果
            barBorderRadius: [30, 30, 0, 0],
          }
        },
      }]
    };
    return option;
  },
  //年度表配置
  getYearBarOption() {
    let _this = this;
    // console.log(_this.data, '333')
    var option = {
      color: ['#3398DB'],
      tooltip: {
        trigger: 'axis',
        hideDelay:100,
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        },
        confine: true,    //是否将提示框限制在图表内
        triggerOn: 'click',
        formatter: function (params, ticket, callback) {
          var res = params[0].name + '年'+'\n'+ '论文引用数量：' + params[0].value;
           return res;
        }
        // position: function(pos, params, dom, rect, size) {
        //   // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
        //   var obj = {
        //     top: 60
        //   };
        //   obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
        //   return obj;
        // }
      },
      grid: {
        left: '3%',
        right: '4%',
        top: 10,
        bottom: 25,
        containLabel: true
      },
      xAxis: [{
        type: 'category',
        data: _this.data.paperNumYear,
        // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        axisTick: {
          alignWithLabel: true
        }
      }],
      yAxis: [{
        type: 'value',
        max: function(value) {
          return value.max +value.max*0.2;
        }
      }],
      series: [{
        name: '',
        type: 'bar',
        barWidth: '40%',
        data: _this.data.yearNumValue,
        // data: [10, 52, 200, 334, 390, 330, 220],
        itemStyle: {
          normal: {
            type: 'linear',
            label: {
              show: false
            },
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [{
                  offset: 0,
                  color: '#9164FE'
                },
                {
                  offset: 1,
                  color: '#62AAFD'
                }
              ]
            ),
            //柱形图圆角，初始化效果
            barBorderRadius: [30, 30, 0, 0],
          }
        },
      }]
    };
    return option;
  },
  //点击我要分享出现弹窗
  shareEvent(e) {
    let _this = this;
    if (e.currentTarget.dataset.item == 0) {
      //用户点击的是我要分享
      _this.setData({
        showPopup: true
      })
    } else {
    }
  },
   //请求是否点赞接口
  isThumbs() {
    let that = this;
    app.authApiRequest('brand/' + that.data.id + '/is_thumbsup/', 'GET', '', res => {
      //为true时表示已经点赞过了，将点赞按钮置为灰色，否则置为蓝色
      if (res.result.thumbsup == true) {
        that.setData({
          isHand: true
        })
      } else {
        that.setData({
          isHand: false
        })
      }
    }, error => {})
  },
  // thumbsEvent(){
  //   let _this=this;
  //   console.log('1111')
  //   if (!wx.canIUse('button.open-type.getUserInfo')) {
  //     wx.showToast({
  //       title: '微信版本低，请升级至高版本',
  //       icon: 'none',
  //       duration: 2000
  //     })
  //   }
  // },
  //用户点击蓝色的点赞按钮，调取用户信息
  bindgetuserinfo(res) {
    let _this = this;
    let data = {
      encrypted_data: res.detail.encryptedData,
      iv: res.detail.iv
    };
    //请求后台的上传用户信息接口
    app.authApiRequest('wx/up_profile/', 'POST', data, res => {
      if (res.code == 1) {
        //上传用户信息成功之后，调取用户点赞接口
        app.authApiRequest('brand/' + _this.data.id + '/thumbs_up/', 'POST', '', res => {
          //点赞成功之后，把点赞按钮置灰
          this.setData({
            isHand: true
          })
          //提示用户点赞成功
          wx.showToast({
            title: '点赞成功',
          })
          //点赞成功之后，重新调用点赞列表接口，刷新列表显示
          _this.http_getThumbs();
        }, error => { })
      }
    }, error => {
      console.log('请求失败')
    })
  },
  //判断用户点击我要分享选择的是什么
  choose(e) {
    let _this = this;
      // 弹窗上的文字分别绑定了参数传过来，0:分享给好友，1：生成图片，2：取消，3：蒙层
    if (e.currentTarget.dataset.item == 0) {
      //调用微信的分享接口
      this.onShareAppMessage();
      _this.setData({
        showPopup: false
      })
    } else if (e.currentTarget.dataset.item == 1) {
      //同意授权之后，才开始绘制画布等操作
      _this.authAlbum();
    } else {
      //关闭弹窗
      _this.setData({
        showPopup: false
      })
    }
  },
  //授权保存图片到手机相册
  authAlbum() {
    let _this = this;
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success: res => {
        _this.setData({
          showPopup: false,
          showPhoto: true
        })
        wx.showLoading({
          title: '图片正在生成中',
          mask: true
        })
        _this.getWXACodeUnlimit();
      },
      fail: res => {
        wx.showModal({
          title: '温馨提示',
          content: '您已拒绝将图片保存到相册，重新授权?',
          success: res => {
            if (res.confirm) {
              wx.openSetting()
            }
          }
        })
      }
    })
  },
  //点击保存，将图片保存到相册
  saveImg() {
    let _this = this;
    var sysInfo = wx.getSystemInfoSync();
    var rpx = sysInfo.windowWidth / 750;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 800 * rpx,
      height: 1320 * rpx,
      destWidth: 800 * 2 * rpx,
      destHeight: 1320 * 2 * rpx,
      canvasId: 'for_save_img',
      quality: 1,
      success(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: res => {
            console.log('222')
            _this.setData({
              saveTips: true
            })
          }
        })
      }
    })
  },
  //画图, mode: 整数,表示放大大小，预览是为1, 保存时为2
  drawShareImg(mode = 1, canvas_id = 'shareImg') {
    let _this = this;
    var rpx;
    var sysInfo = wx.getSystemInfoSync();
    var rpx = sysInfo.windowWidth / 750;
    rpx = rpx * mode;
    const ctx = wx.createCanvasContext(canvas_id);
    //绘制圆角矩形
    ctx.drawImage('../../resource/share1.png', 0, 0, 400 * rpx, 660 * rpx);
    //绘制小程序码
    ctx.drawImage(_this.data.codeUrl, 50 * rpx, 540 * rpx, 80 * rpx, 80 * rpx)
    //绘制品牌名字
    ctx.fillStyle = "#FDB52A";
    ctx.setFontSize(32 * rpx);
    ctx.setShadow(0, 4 * rpx, 2 * rpx, 'rgba(12, 42, 132, 0.3)')
    ctx.fillText(_this.data.brandName, 60 * rpx, 150 * rpx);
    //重置阴影颜色
    ctx.setShadow(0, 0, 0, '#fff')
    //绘制知了指数
    ctx.setShadow(0, 6* rpx, 4 * rpx, 'rgba(12,42,132,0.3)')
    ctx.setFontSize(32 * rpx);
    ctx.fillStyle = "#fff";
    ctx.fillText("知了指数：", 100 * rpx, 200 * rpx);
    ctx.fillText(_this.data.indexScore, 250 * rpx, 200 * rpx);
    //重置阴影颜色
    ctx.setShadow(0, 0, 0, '#fff')
    ctx.setFillStyle("#333");
    ctx.setFontSize(16 * rpx);
    var text = _this.data.brandBrief;
    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    ctx.setFontSize(16 * rpx);
    ctx.setFillStyle("#333");
    for (var a = 0; a < chr.length; a++) {
      if (ctx.measureText(temp).width < 400 * rpx) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);
    //如果数组长度大于2 则截取前两个
    if (row.length > 3) {
      var rowCut = row.slice(0, 3);
      var rowPart = rowCut[2];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (ctx.measureText(test).width < 660 * rpx) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示三行，超出的用...表示
      rowCut.splice(2, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      ctx.fillText(row[b], 30 * rpx, (340 + b * 30) * rpx, 330 * rpx);
    }
    //    //一大段文字自动换行结束
    ctx.setFontSize(16 * rpx);
    ctx.fillStyle = "#808080";
    ctx.fillText('生产商：', 30 * rpx, 440 * rpx);
    ctx.fillStyle = "#808080";
    ctx.fillText(_this.data.provider, 100 * rpx, 440 * rpx);
    ctx.fillStyle = "#808080";
    ctx.fillText('经营地址：', 30 * rpx, 470 * rpx);
    ctx.fillStyle = "#808080";
    ctx.fillText(_this.data.address.slice(0, 17), 100 * rpx, 470* rpx);
    ctx.fillText(_this.data.address.slice(17, _this.data.address.length), 100 * rpx, 490 * rpx)
    ctx.setFillStyle('#666666');
    ctx.fillRect(150 * rpx, 550 * rpx, 1 * rpx, 70 * rpx)
    ctx.setFontSize(18 * rpx);
    ctx.fillStyle = "#666666";
    ctx.fillText('长按小程序码', 170 * rpx, 575 * rpx, );
    ctx.fillStyle = "#666666";
    ctx.fillText('知了指数·关注品牌', 170 * rpx, 610 * rpx, );
    ctx.draw(false, function() {
      if (mode == 1) {
        wx.hideLoading();
      }
    });
  },
  //请求后台生成二维码的接口
  getWXACodeUnlimit() {
    let _this = this;
    let data = { page: 'pages/indexDetail/indexDetail', app_id: 'wx1f0c582daae24787',scene:'id='+_this.data.id};
    app.authApiRequest('wx/get_wxa_code/', 'POST', data, res => {
      if (res.code == 1) {
        //取出二维码路径，保存为本地路径
        wx.getImageInfo({
          src: res.result.url_path,
          success(res){
            let Path = res.path;
            _this.setData({
              codeUrl: Path,
            })
            _this.drawShareImg(2, 'for_save_img');
            _this.drawShareImg();
          }
        })
      }
    }, error => {
      wx.hideLoading();
      wx.showToast({
        title: '生成图片失败',
        icon:'none',
        duration: 2000
      })
    })
  },
  //点击弹窗上的关闭按钮，关闭生成二维码图片的弹窗
  closeShareImg() {
    let _this = this;
     //重新初始化图表
    setTimeout(function() {
      _this.init_indexLine();
      _this.init_monthBar();
      _this.init_yearBar();
    }, 500)
    this.setData({
      showPhoto: false
    })
  },
  //跳转至首页
  toHome() {
    wx.reLaunch({ //跳转至指定页面并关闭其他打开的所有页面（这个最好用在返回至首页的的时候）
      url: '/pages/index/index'
    })
  },
  //分享给朋友
  onShareAppMessage(res) {
    let _this = this;
    return {
      title: '知了指数',
      path: 'pages/indexDetail/indexDetail?id='+ _this.data.id,
      success: function(res) {
        // 转发成功之后的回调 　　　
        if (res.errMsg == 'shareAppMessage:ok') {

          　}
      },
      fail: function(res) {

      },
      complete: function(res) {

      }
    }
  }

});